Vue.component('operator-inventory-view', {
  data() {
    return {
      inventory: [],
      loading: false,
      searchForm: {
        product_name: '',
        category: '',
        low_stock: false
      },
      categories: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 统计信息
      statistics: {
        total_products: 0,
        total_value: 0,
        low_stock_count: 0,
        zero_stock_count: 0
      },
      // 低库存预警
      lowStockAlert: {
        visible: false,
        products: []
      }
    };
  },
  methods: {
    async loadCategories() {
      try {
        const response = await categoryAPI.getCategoryTree();
        console.log('操作员分类树API响应:', response);
        if (response && response.code === 200) {
          this.categories = this.buildCategoryOptions(response.data);
          console.log('操作员分类树数据已设置:', this.categories);
        } else {
          console.error('操作员分类树API响应失败:', response);
        }
      } catch (error) {
        console.error('获取操作员分类树失败:', error);
        this.$message.error(error.message || '获取分类树失败');
      }
    },
    buildCategoryOptions(categories, level = 0) {
      let options = [];
      categories.forEach(category => {
        const prefix = '　'.repeat(level);
        options.push({
          value: category.id,
          label: prefix + category.name
        });
        if (category.children && category.children.length > 0) {
          options = options.concat(this.buildCategoryOptions(category.children, level + 1));
        }
      });
      return options;
    },
    async loadInventory() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          search: this.searchForm.product_name,
          category_name: this.searchForm.category,
          low_stock: this.searchForm.low_stock
        };
        
        // 清理空参数，但保留布尔值
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === null || params[key] === undefined) {
            delete params[key];
          }
        });
        
        // 确保低库存参数始终发送
        if (this.searchForm.low_stock !== undefined) {
          params.low_stock = this.searchForm.low_stock;
        }
        
        const response = await inventoryAPI.getInventory(params);
        console.log('库存API响应:', response);
        if (response.data && response.data.inventory) {
          // 后端直接返回数组，需要转换字段名
          this.inventory = response.data.inventory.map(item => ({
            product_id: item.product_id,
            product_name: item.product_name,
            category: item.category_name,
            supplier_name: item.supplier_name,
            stock_quantity: item.current_stock,
            min_stock: item.min_stock,
            max_stock: item.max_stock,
            unit_price: item.unit_price,
            cost_price: item.cost_price,
            total_value: item.stock_value,
            last_updated: item.last_updated
          }));
          this.total = response.data.pagination.total;
        } else {
          console.error('API返回失败:', response);
          this.$message.error(response.msg || '获取库存数据失败');
        }
      } catch (error) {
        console.error('获取库存列表失败:', error);
        this.$message.error(error.message || '获取库存列表失败');
      } finally {
        this.loading = false;
      }
    },
    async loadStatistics() {
      try {
        const response = await inventoryAPI.getStatistics();
        if (response.data) {
          this.statistics = response.data;
        }
      } catch (error) {
        console.error('获取库存统计失败:', error);
      }
    },
    async loadLowStockAlert() {
      try {
        const response = await inventoryAPI.getLowStockProducts();
        if (response.data) {
          this.lowStockAlert.products = response.data;
          if (response.data.length > 0) {
            this.lowStockAlert.visible = true;
          }
        }
      } catch (error) {
        console.error('获取低库存商品失败:', error);
      }
    },
    closeLowStockAlert() {
      this.lowStockAlert.visible = false;
    },
    handleSearch() {
      this.currentPage = 1;
      this.loadInventory();
    },
    handleReset() {
      this.searchForm = {
        product_name: '',
        category: '',
        low_stock: false
      };
      this.currentPage = 1;
      this.loadInventory();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadInventory();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadInventory();
    },
    getStockStatus(row) {
      if (row.stock_quantity <= row.min_stock) {
        return { type: 'danger', text: '库存不足' };
      } else if (row.stock_quantity <= row.min_stock * 1.5) {
        return { type: 'warning', text: '库存偏低' };
      } else {
        return { type: 'success', text: '库存正常' };
      }
    }
  },
  async mounted() {
    await Promise.all([
      this.loadCategories(),
      this.loadInventory(),
      this.loadStatistics(),
      this.loadLowStockAlert()
    ]);
  },
  template: `
    <div class="inventory-view">
      <el-card>
        <div slot="header">
          <span>库存查看</span>
        </div>
        
        <!-- 搜索表单 -->
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.product_name" placeholder="请输入商品名称" clearable size="small"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable size="small">
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="低库存">
            <el-switch v-model="searchForm.low_stock" size="small"></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="small">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 库存表格 -->
        <el-table :data="inventory" v-loading="loading" border>
          <el-table-column prop="product_name" label="商品名称" min-width="150"></el-table-column>
          <el-table-column prop="category" label="分类" width="120">
            <template slot-scope="scope">
              {{ categories.find(c => c.value === scope.row.category)?.label || scope.row.category }}
            </template>
          </el-table-column>
          <el-table-column prop="supplier_name" label="供应商" width="120"></el-table-column>
          <el-table-column prop="stock_quantity" label="当前库存" width="100">
            <template slot-scope="scope">
              <span :class="getStockStatus(scope.row).type === 'danger' ? 'text-danger' : ''">
                {{ scope.row.stock_quantity }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="min_stock" label="最低库存" width="90"></el-table-column>
          <el-table-column prop="max_stock" label="最高库存" width="90"></el-table-column>
          <el-table-column prop="cost_price" label="成本价" width="90">
            <template slot-scope="scope">
              ¥{{ Number(scope.row.cost_price).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="unit_price" label="销售单价" width="100">
            <template slot-scope="scope">
              ¥{{ Number(scope.row.unit_price).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="total_value" label="库存价值" width="110">
            <template slot-scope="scope">
              ¥{{ Number(scope.row.total_value).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column label="库存状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStockStatus(scope.row).type" size="small">
                {{ getStockStatus(scope.row).text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="last_updated" label="最后更新" width="150">
            <template slot-scope="scope">
              {{ new Date(scope.row.last_updated).toLocaleString() }}
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right;">
        </el-pagination>
      </el-card>
      
      <!-- 低库存预警对话框 -->
      <el-dialog
        title="低库存预警"
        :visible.sync="lowStockAlert.visible"
        width="800px"
        :close-on-click-modal="false">
        <div style="margin-bottom: 15px;">
          <el-alert
            title="以下商品库存不足，请及时补货！"
            type="warning"
            :closable="false"
            show-icon>
          </el-alert>
        </div>
        <el-table :data="lowStockAlert.products" border>
          <el-table-column prop="name" label="商品名称" min-width="150"></el-table-column>
          <el-table-column prop="sku" label="商品编码" width="120"></el-table-column>
          <el-table-column prop="min_stock" label="最低库存" width="100"></el-table-column>
          <el-table-column prop="current_stock" label="当前库存" width="100">
            <template slot-scope="scope">
              <span style="color: #f56c6c; font-weight: bold;">{{ scope.row.current_stock }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="shortage" label="缺货数量" width="100">
            <template slot-scope="scope">
              <span style="color: #f56c6c; font-weight: bold;">{{ scope.row.shortage }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="unit_price" label="单价" width="100">
            <template slot-scope="scope">
              ¥{{ Number(scope.row.unit_price).toLocaleString() }}
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="closeLowStockAlert">我知道了</el-button>
        </div>
      </el-dialog>
      
      <style>
        .text-danger {
          color: #f56c6c;
          font-weight: bold;
        }
      </style>
    </div>
  `
});
